package com.tanhua.api;

import com.tanhua.api.RecommendUserService;
import com.tanhua.sso.pojo.RecommendUser;
import com.tanhua.sso.pojo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class RecommendServiceImpi implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询最高缘分值最高一个
    @Override
    public RecommendUser selectByid(Long id) {
        Criteria toUserId = Criteria.where("toUserId").is(id);
        Query query = Query.query(toUserId).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    //批量查询
    @Override
    public List<RecommendUser> selectAll(Long toUserId) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        List<RecommendUser> list = mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))), RecommendUser.class);
        return list;
    }

    //查看当前查看的佳人信息
    @Override
    public RecommendUser selectOne(Long id, Long userId) {
        Criteria criteria = Criteria.where("userId").is(id).and("toUserId").is(userId);
        RecommendUser recommendUser = mongoTemplate.findOne(Query.query(criteria), RecommendUser.class);
        return recommendUser;
    }

    /*查看推荐好友,取出喜欢和不喜欢*/
    @Override
    public List<RecommendUser> selectCards(Long userId, int i) {
        //获取喜欢和不喜欢的人id
        Criteria criteria = Criteria.where("userId").is(userId);
        List<UserLike> userLikes = mongoTemplate.find(Query.query(criteria), UserLike.class);
        List<Long> likeIdList = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        //查询条件
        Criteria nin = Criteria.where("toUserId").is(userId).and("userId").nin(likeIdList);
        //使用统计函数
        TypedAggregation<RecommendUser> recommendUserTypedAggregation=TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(nin),Aggregation.sample(i));
        AggregationResults<RecommendUser> results = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        List<RecommendUser> mappedResults = results.getMappedResults();
        return mappedResults;
    }

}
